<?php
/**
 * 操作员模型
 *
 * Author:李强
 * Company:上海煦鸣网络科技有限公司
 * Date:2018-01-03
 */

namespace App\Models;

use App\Traits\Common;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Zizaco\Entrust\Traits\EntrustUserTrait;

class User extends Authenticatable
{
    //
    use EntrustUserTrait, Notifiable, Common;
    protected $table = "users";
    protected $guarded = [];
    protected $primaryKey = "id";
    public $timestamps = true;

    /**
     * 可填充字段
     * @var array
     */
    protected $fillable = [
        'nickname', 'email', 'password', 'mobile', 'avatar'
    ];

    /**
     * 隐藏字段
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token'
    ];

    /**
     * 判断管理员是否有某一或某些角色
     *
     * @param $roles
     * @return bool
     */
    public function isInRole($roles)
    {
        return !!$roles->intersect($this->roles)->count();
    }

    /**
     * 给用户分配角色
     *
     * @param $role
     * @return mixed
     */
    public function assignRole($role)
    {
        return $this->roles()->save($role);
    }

    /**
     * 取消用户分配角色
     *
     * @param $role
     * @return mixed
     */
    public function deleteRole($role)
    {
        return $this->roles()->detach($role);
    }

    /**
     * 判断是否存在某一权限
     *
     * @param $permission
     * @return bool
     */
    public function hasPermission($permission)
    {
        return $this->isInRole($permission->roles);
    }

    /**
     * 管理员是否存在
     *
     * @param $type =1 mobile2邮箱
     * @param $value
     * @param $id
     */
    public static function isExists($type = 1, $value = '', $id = 0)
    {
        $where = [];
        if ($type == 1) {
            $where[] = ['mobile', '=', $value];
        } else {
            $where[] = ['email', '=', $value];
        }
        if ($id > 0) {
            $where[] = ['id', '!=', $id];
        }
        $admin = self::where($where)->first();
        return !is_null($admin) ? true : false;
    }
}
